package com.authentications.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.authentications.utils.ResultBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName jwtAccessDeniedHandler
 * @Author xiezhuocai
 * @Description 当用户在没有授权的时候，返回的指定信息
 * @Date 2021/12/20 8:36
 */
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //String reason = "统一处理，原因：" + e.getMessage();
        httpServletResponse.getWriter().write(JSONObject.toJSONString(ResultBean.error("System error",500, e.getMessage())));
        httpServletResponse.getWriter().close();
        httpServletResponse.flushBuffer();
    }
}
